package com.sfy.course.aggregation.controller;

import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import com.sfy.common.dto.CourseDTO;
import com.sfy.common.dto.InstructorDTO;
import com.sfy.course.aggregation.msmapper.MsCourseDetailMapper;
import com.sfy.course.aggregation.vo.CourseDetailVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/api/courses")
@RequiredArgsConstructor
@Slf4j
public class CourseAggregationController {
    private final RestTemplate restTemplate;
    private final MsCourseDetailMapper msCourseDetailMapper;
    private final EurekaClient eurekaClient;
//    //定义访问课程原子服务的地址
//    private static final String COURSE_SERVICE_URL = "http://localhost:9000/api/courses/";
//    //定义访问课程原子服务的地址
//    private static final String INSTRUCTOR_SERVICE_URL = "http://localhost:8000/api/instructors/";

    @GetMapping("/{courseId}")
    public ResponseEntity<CourseDetailVO> getCourseDetail(@PathVariable("courseId") Integer courseId) {
        InstanceInfo courseInstanceInfo = eurekaClient.getNextServerFromEureka("course-service", false);
        String courseServiceUrl = "http://"+courseInstanceInfo.getHostName() + ":"+courseInstanceInfo.getPort()+"/api/courses/";

        ResponseEntity<CourseDTO> courseResponseEntity = restTemplate
                .getForEntity(courseServiceUrl + courseId, CourseDTO.class);
        if(!courseResponseEntity.getStatusCode().is2xxSuccessful() || courseResponseEntity.getBody() == null) {
            return ResponseEntity.notFound().build();
        }
        CourseDTO courseDTO = courseResponseEntity.getBody();

        InstanceInfo userInstanceInfo = eurekaClient.getNextServerFromEureka("user-service", false);
        String instanceServiceUrl = "http://"+userInstanceInfo.getHostName() + ":"+userInstanceInfo.getPort()+"/api/instructors/";
        ResponseEntity<InstructorDTO> instructorResponseEntity = restTemplate
                .getForEntity(instanceServiceUrl + courseDTO.getInstructorId(), InstructorDTO.class);
        InstructorDTO instructorDTO = null;
        if (instructorResponseEntity.getStatusCode().is2xxSuccessful() && instructorResponseEntity.getBody() != null) {
            instructorDTO = instructorResponseEntity.getBody();
        }else {
            log.error("获取讲师信息失败，失败的讲师ID:{}", courseDTO.getInstructorId());
        }
        return ResponseEntity.ok(msCourseDetailMapper.toCourseDetailVO(courseDTO, instructorDTO));
    }
}
